﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using System.Windows.Media;
using Asteroids.Game.PowerUps;

namespace Asteroids.Game
{
    class Asteroid:EntityBase
    {
        private const int AsteroidsPerSplit = 3;
        private const double AsteroidDropProbability = 0.15;

        public int NumSplits { get; set; }
        public static Random Random { get { return _random ?? (_random = new Random()); }
            set
            {
                if (_random == null)
                {
                    _random = new Random();
                }
            } 
        }
        private static Random _random { get; set; }

        public Asteroid(int numSplits, Coordinate loc) : base()
        {
            NumSplits = numSplits;
            Radius = numSplits * 8; // Makes the size of the asteroid relative to the number of times it can split.

            Location = loc;

            var angle = Random.NextDouble() *(2*Math.PI);
            var magnitude = Random.NextDouble()*3+2;

            Velocity = new PolarCoordinate(angle, magnitude);

            VertexData = GetRandomVertexData();

            Brush = Brushes.White;
        }

        private List<PolarCoordinate> GetRandomVertexData()
        {
            var templist = new List<PolarCoordinate>();
            
            var numOfPoints = Random.Next(5, 18);
            var radiusMin = .6f;
            var radiusMax = 1.3f;

            for (double i = 0; i < 2 * Math.PI; i += (2 * Math.PI / numOfPoints))
            {
                templist.Add(new PolarCoordinate(i,Radius*(Random.NextDouble()*(radiusMax-radiusMin)+radiusMin)));
            }

            return templist;
        }

        public override void Collide(CollideEventArgs e)
        {
            for (int i = 0; i < AsteroidsPerSplit && NumSplits > 1; i++)
                Game.Instance.PendingAsteroids.Add(CreateAsteroid(NumSplits - 1, () => Location));
            Dead = true;
            if (Game.Random.NextDouble() < AsteroidDropProbability)
            {
                Console.WriteLine("Spawning an Asteroid powerup...");
                Game.Instance.PowerUps.Add(PowerUp.GetRandomPowerUp(Location));
            }
        }

        public override bool IsVulnerable()
        {
            return true;
        }

        public static Asteroid CreateAsteroid(int numSplits, Func<Coordinate> getLocation)
        {
            return new Asteroid(numSplits, getLocation());
        }
    }
}
